package com.reef.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.reef.dto.BookDto;
import com.reef.entity.Book;
import com.reef.entity.Result;
import com.reef.service.BookService;
@RestController
public class BookController {
	@Autowired
  private BookService bookService;
	//添加图书
	@RequestMapping("/insertbook")
	public Object addbook(Book book) {
		Book i=bookService.insertBook(book);
		if(i!=null) {
			Result result = new Result("添加成功","",true);
			return result;
		}else {
			Result result = new Result("添加失败","",false);
			return result;
		}
		//return obj;
	}
	/**
	 * 修改
	 */
	@RequestMapping(value = "/update",method = RequestMethod.POST)
	public Object upBook(Book book) {
		Book i=bookService.updateBook(book);
		if(i!=null) {
			Result result = new Result("修改成功","",true);
			return result;
		}else {
			Result result = new Result("修改失败","",false);
			return result;
		}
	}
	
	/**
	 * 多条件动态查询
	 */
	@RequestMapping("/queryAll")
	public Object findByCondition(BookDto bDto,int page,int limit) {
		//getTotalElements()指实体中有多少元素
		//分页查询 springBoot2.0以下版本用new 实例化，2.0以上版本使用的是PageRequest
		Pageable pageable = PageRequest.of(page-1, limit);
		Page<Book> pagelist  = bookService.findByCondition(bDto, pageable);
		Map<String, Object> map =new HashMap<String, Object>();
		map.put("code", 0);
		map.put("msg", "");
		map.put("count", pagelist.getTotalElements());
		map.put("data", pagelist.getContent());
		return map;
	}
	@RequestMapping("/updateByNumber")
	public Object updateByNumber(int number, int lendnum, int book_id) {
		int i = bookService.updateByNumber(number, lendnum, book_id);
		if(i>0) {
			Result result = new Result("修改成功","",true);
			return result;
		}else {
			Result result = new Result("修改失败","",false);
			return result;
		}
	}
	@RequestMapping("/updateByBookNumber")
	public Object updateByBookNumber(int number, int book_id) {
		int i = bookService.updateByBookNumber(number, book_id);
		if(i>0) {
			Result result = new Result("修改成功","",true);
			return result;
		}else {
			Result result = new Result("修改失败","",false);
			return result;
		}
	}
}
